package goroutine

import (
	"fmt"
	"github.com/panjf2000/ants/v2"
	"log"
	"runtime"
	"sync"
	"time"
)

var wg sync.WaitGroup

func GoroutineOddAndEven() {
	wg.Add(2)

	odd := func() {
		defer wg.Done()
		for i := 1; i < 10; i += 2 {
			fmt.Println("我是奇数：", i)
			time.Sleep(300 * time.Millisecond)
		}
	}

	even := func() {
		defer wg.Done()
		for i := 2; i <= 10; i += 2 {
			fmt.Println("我是偶数：", i)
			time.Sleep(300 * time.Millisecond)
		}
	}

	go odd()
	go even()

	wg.Wait()
}

func GoroutineAnts() {
	go func() {
		for {
			fmt.Println("NumGoroutine:", runtime.NumGoroutine())
			time.Sleep(500 * time.Millisecond)
		}
	}()

	size := 1024
	pool, err := ants.NewPool(size)
	if err != nil {
		log.Fatalln(err)
	}

	defer pool.Release()

	for {
		err := pool.Submit(func() {
			_ = make([]int, 1024)
			fmt.Println("in goroutine")
			time.Sleep(100 * time.Second)
		})

		if err != nil {
			log.Fatalln(err)
		}
	}
}
